import { defineComponent, reactive, ref, Ref, toRefs, watchEffect } from 'vue'
import BannerItem from './BannerItem'

import useAsyncFn from 'hooks/useAsyncFn'
import { useInterval } from 'hooks/useInterval'

import { TARGET_TYPE } from 'apis/types/business'

import personalizedApis from 'apis/personalized'

import styles from './style.module.scss'

export default defineComponent({
  name: '',
  setup() {
    const currentMid: Ref<number> = ref(0)
    const [state, getBannerFn] = useAsyncFn(personalizedApis.getBanner)

    getBannerFn()

    const bannersClassName = (banners: any[]) => {
      const len = banners.length
      const left = (currentMid.value - 1 + len) % len
      const right = (currentMid.value + 1) % len
      return {
        [currentMid.value]: styles.middle,
        [left]: styles.left,
        [right]: styles.right,
      }
    }
    const handleMidChange = (index: number) => {
      stop()
      currentMid.value = index
    }

    const [stop, start] = useInterval(
      () => {
        const { result: banners = [] } = state
        if (banners.length) {
          const len = banners.length || 0
          currentMid.value = (currentMid.value + 1) % len
        }
      },
      3000,
      false,
    )

    return () => {
      const { result: banners = [], loading: isGettingBanner } = state

      return isGettingBanner ? (
        <spinner />
      ) : (
        <>
          <div class={styles.root}>
            <div class={styles.banners}>
              {banners.map(
                ({ imageUrl, typeTitle, targetId, targetType }, index) => {
                  const className =
                    bannersClassName(banners)[index] || styles.hidden
                  const isMusicType = targetType === TARGET_TYPE.MUSIC
                  return (
                    <BannerItem
                      key={imageUrl}
                      typeTitle={typeTitle}
                      imageUrl={imageUrl}
                      className={[className, isMusicType ? styles.enabled : '']}
                    />
                  )
                },
              )}
            </div>
            <div class={styles.dots}>
              {banners.map(({ imageUrl }, index: number) => {
                return (
                  <div
                    key={imageUrl}
                    class={[
                      styles.dot,
                      index === currentMid.value ? styles.active : '',
                    ]}
                    onMouseover={() => handleMidChange(index)}
                    onMouseleave={() => start()}
                  />
                )
              })}
            </div>
          </div>
        </>
      )
    }
  },
})
